package com.dushuren.project.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/***
 * 自动redis序列器
 */

@Configuration
public class RedisTemplateConfig {


  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
	redisTemplate.setConnectionFactory(redisConnectionFactory);
	redisTemplate.setKeySerializer(new StringRedisSerializer());
	redisTemplate.setValueSerializer(new StringRedisSerializer());
	redisTemplate.setHashKeySerializer(new StringRedisSerializer());
	redisTemplate.setHashValueSerializer(new StringRedisSerializer());
	return redisTemplate;
  }

  @Bean("kryoRedisTemplate")
  public RedisTemplate<String, Object> kryoRedisTemplate(LettuceConnectionFactory connectionFactory) {
	// key序列化
	RedisSerializer<?> keySerializer = new StringRedisSerializer();
	// value序列化
	KryoRedisSerializerConfig<Object> valueSerializer = new KryoRedisSerializerConfig<>();
	// 配置redisTemplate
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
	redisTemplate.setConnectionFactory(connectionFactory);
	// key序列化
	redisTemplate.setKeySerializer(keySerializer);
	// value序列化
	redisTemplate.setValueSerializer(valueSerializer);
	// Hash key序列化
	redisTemplate.setHashKeySerializer(keySerializer);
	// Hash value序列化
	redisTemplate.setHashValueSerializer(valueSerializer);
	redisTemplate.afterPropertiesSet();
	return redisTemplate;
  }

}
